import React, { Component, Fragment } from 'react'
import { Card, Table, Breadcrumb, Tooltip, Image, Button, Modal, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { fetchItem, delItem } from '_api'
import { Link } from 'react-router-dom';
// dayjs一个转化时间戳的包，可以显示多少时间之前和时间格式化
import dayjs from 'dayjs'
// 导出excel表
const ExportJsonExcel = require('js-export-excel')

export default class Home extends Component {
  state = {
    items: [], // 商品列表
    total: 0, // 商品总数
    page: 1, // 默认页
    pageSize: 10, // 每页的商品数目
    isLoading: false,
    columns: [
      {
        title: '商品名称',
        dataIndex: 'itemName',
        key: 'itemName',
      },
      {
        title: '商品价格',
        dataIndex: 'itemPrice',
        key: 'itemPrice',
      },
      {
        title: '商品描述',
        dataIndex: 'itemDesc',
        render: (itemDesc) => {
          return (
            <Tooltip title={itemDesc}>
              <span>
                {itemDesc.length > 10 ? itemDesc.substr(0, 10) + '...' : itemDesc}
              </span>
            </Tooltip>
          )
        },
        key: 'itemDesc',
      },
      {
        title: '商品封面',
        dataIndex: 'thumb',
        render: (thumb) => {
          return (
            <Image
              width={100}
              src={thumb} />
          )
        },
        key: 'thumb',
      },
      {
        title: '上架时间',
        dataIndex: 'createDate',
        render: (createDate) => {
          return (
            <span>
              {dayjs(createDate).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          )
        },
        key: 'createDate',
      },
      {
        title: '商品详情',
        dataIndex: 'context',
        render: (context) => {
          return (
            <div dangerouslySetInnerHTML={{ __html: context }}></div>
          )
        },
        key: 'context',
      },
      {
        title: '操作',
        render: (value) => {
          return (
            <Fragment>
              <Button type="primary" size="small" shape="round" style={{ marginRight: 10 }} onClick={() => {
                this.props.history.push(`/admin/itemupdate/${value.id}`)
              }}>修改</Button>
              <Button type="danger" size="small" shape="round" onClick={() => {
                this.delItems(value.id)
              }}>删除</Button>
            </Fragment>
          )
        },
        key: 'value',
      }
    ]
  };
  render() {
    return (
      <Card extra={
        <Fragment>
          <Button type="primary"><Link to="/admin/itemadd">增加商品</Link></Button>
          <Button onClick={this.exportExcel}>导出Excel</Button>
        </Fragment>
      }
        title={
          // 面包屑导航
          <Breadcrumb>
            <Breadcrumb.Item><Link to="/admin/dashboard">仪表盘</Link></Breadcrumb.Item>
            <Breadcrumb.Item>商品列表</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Table
          pagination={{
            showSizeChanger: true,
            page: this.state.page,
            onChange: this.onShowSizeChange,
            pageSize: this.state.pageSize,
            total: this.state.total
          }}
          loading={this.state.isLoading}
          columns={this.state.columns}
          dataSource={this.state.items}
          rowKey="id" />
      </Card>
    )
  };
  componentDidMount() {
    this.fetchItems()
  };
  // 请求商品列表
  fetchItems = () => {
    // 开启loading
    this.setState({
      isLoading: true
    })
    fetchItem({
      page: this.state.page,
      pageSize: this.state.pageSize
    }).then(res => {
      // 关闭loading
      this.setState({
        isLoading: false
      })
      if (res.data.code === 200) {
        this.setState({
          items: res.data.data.lists,
          total: res.data.data.total
        })
      }
    })
  };
  // 删除商品
  delItems = (id) => {
    Modal.confirm({
      title: '你真的要删除此商品吗？',
      icon: <ExclamationCircleOutlined />,
      content: '删除不可恢复哟！',
      onOk:() => {
        delItem({ id }).then(res => {
          if (res.data.code === 200) {
            message.success('删除成功', 1, () => {
              this.props.history.go(0)
            } )
          }
        })
      },
    })
    
  }
  // 分页显示
  onShowSizeChange = (current, size) => {
    this.setState({
      page: current,
      pageSize: size
    }, () => {
      this.fetchItems()
    })
  };
  // 导出Excel
  exportExcel = () => {
    // 对导出的table数据进行处理
    const option = {}
    option.fileName = 'goodsList'
    const sheetData = this.state.items
    option.datas = [
      {
        sheetData,
        // 每一个sheet的name
        sheetName: "商品数据",
        // 列标题
        sheetHeader: ['id', '商品名称', '商品价格', '商品描述', '商品封面', '上架时间', '商品详情'],
        // 每列宽度
        columnWidths: [5, 8, 5, 20, 20, 5, 8],
      }
    ]
    const toExcel = new ExportJsonExcel(option)
    toExcel.saveExcel()
  }
}
